<!--markdown 编辑器说明文档 https://github.com/hinesboy/mavonEditor-->
<template>
  <div style="height: 100%">
    <navigation></navigation>

    <el-row>
      <el-col :sm="{span:24}" :xl="{span:14,offset:5}" :lg="{span:18,offset:3}" :md="{span:18,offset:3}">
        <div style="margin-top: 15px">
          <el-page-header class="title" @back="goBack" title="返回" content="编写文章">
          </el-page-header>

          <div class="button">
            <el-button icon="el-icon-tickets" size="mini" v-on:click="save">存草稿</el-button>
            <el-button type="primary" size="mini" icon="el-icon-s-promotion" v-on:click="dialogFormVisible = true">发布
            </el-button>
          </div>
        </div>

        <el-input style="margin-bottom: 15px;}" v-model="title" placeholder="请输入文章标题"></el-input>

        <div style="clear: both"></div>

        <mavon-editor ref=md @save="ctrlS" @change="change" @imgAdd="imgAdd" @imgDel="imgDel" class="editor"
                      v-model="value"/>
      </el-col>
    </el-row>


    <el-dialog title="发布文章" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="文章类型">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option label="原创" value="1"></el-option>
            <el-option label="转载" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布形式">
          <el-select v-model="form.pushType" placeholder="请选择">
            <el-option label="公开" value="1"></el-option>
            <el-option label="私密" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择分类">
          <el-select v-model="form.categoryId" placeholder="请选择">
            <el-option v-for="category in categoryList" :label="category.name"
                       :value="category.categoryId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="push">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {mavonEditor} from 'mavon-editor';
import Navigation from "../components/Navigation";
import qs from 'qs'

const axios = require('axios')

export default {
  components: {
    "mavon-editor": mavonEditor,
    "navigation": Navigation
  },
  data() {
    return {
      value: '',
      title: '',
      // 文章id
      id: '',
      markdown: '',
      html: '',
      categoryList: [],
      dialogFormVisible: false,
      form: {
        type: '',
        pushType: '',
        categoryId: ''
      }
    }
  },
  mounted() {
    this.id = this.$route.query.id;
    if (this.id) {
      axios.get("/api/content/edit/get_content?id=" + this.id).then((res) => {
        if (res.data.code === 200) {
          this.title = res.data.data.title;
          this.html = res.data.data.html;
          this.value = res.data.data.content;
          this.id = res.data.data.id;
          if (res.data.data.type === 1) {
            this.form.type = '原创';
          } else if (res.data.data.type === 2) {
            this.form.type = '转载';
          }
          if (res.data.data.pushType === 1) {
            this.form.pushType = '公开';
          } else if (res.data.data.pushType === 2) {
            this.form.pushType = '私密';
          }

        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(() => {
        this.$message.error("系统繁忙，请稍后再试！");
      })
    }
    axios.get("/api/category/list").then(res => {
      this.categoryList = res.data.data;
      if (this.id) {
        axios.get("/api/content/category?contentId=" + this.id).then(res => {
          if (res.data.code === 200) {
            this.form.categoryId = res.data.data;
          }
        })
      }
    });
  },
  methods: {
    imgAdd(pos, $file) {
      let formData = new FormData();
      formData.append('file', $file);
      axios({
        url: '/api/content/upload_img',
        method: 'post',
        data: formData,
        headers: {'Content-Type': 'multipart/form-data'},
      }).then((res) => {
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        // $vm.$img2Url 详情见本页末尾
        if (res.data.code === 200) {
          this.$refs.md.$img2Url(pos, res.data.data.url);
        } else {
          this.$message.error(res.data.msg);
        }

      })
    },
    imgDel(pos) {
      let imgUrl = pos[0];
      console.info("删除的imgUrl:", imgUrl);
      if (imgUrl === '' || imgUrl === null) {
        return;
      }
      axios({
        url: "/api/content/del_img",
        method: "POST",
        data: {
          "url": imgUrl
        }
      }).then(res => {
        console.info("res=", res)
      }).catch(e => {
        console.error(e)
      })
    },
    // 监听编辑框内容变化
    change(value, render) {
      this.markdown = value;
      this.html = render;
      console.log('markdown:', value, 'html:', render)
    },

    // ctrl+s手动保存事件
    ctrlS() {
      this.save()
    },

    //保存草稿
    save() {
      if (!this.title) {
        this.$message.warning("文章标题不能为空！");
        return;
      }
      if (!this.html || !this.markdown) {
        this.$message.warning("文章内容不能为空！");
        return;
      }
      axios.post("/api/content/saveDraft",
        qs.stringify({
          title: this.title.trim(),
          html: this.html,
          content: this.value,
          id: this.id
        })).then((res) => {
        this.id = res.data.data.id;
        this.$message.success("保存成功！")
      }).catch(() => {
        this.$message.error("保存失败，请重试！");
      })
      console.log(this.value)
    },
    goBack() {
      this.$router.go(-1);
    },
    // 发布文章
    push() {
      if (!this.title) {
        this.$message.warning("文章标题不能为空！");
        return;
      }
      if (!this.html || !this.markdown) {
        this.$message.warning("文章内容不能为空！");
        return;
      }
      if (!this.form.type) {
        this.$message.warning("请选择文章类型！");
        return;
      }
      if (!this.form.pushType) {
        this.$message.warning("请选择发布形式！");
        return;
      }

      if (this.form.type === '原创') {
        this.form.type = 1;
      } else if (this.form.type === '转载') {
        this.form.type = 2;
      }

      if (this.form.pushType === '公开') {
        this.form.pushType = 1;
      } else if (this.form.pushType === '私密') {
        this.form.pushType = 2;
      }

      axios.post("/api/content/add_content", qs.stringify({
        title: this.title.trim(),
        html: this.html,
        content: this.markdown,
        id: this.id,
        type: this.form.type,
        pushType: this.form.pushType,
        categoryId: this.form.categoryId
      })).then((res) => {
        if (res.data.code === 200) {
          this.$message.success("发布成功！");
          this.dialogFormVisible = false;
          this.$router.push({
            path: "/my-content",
            query: {
              activityIndex: '2'
            }

          })
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(() => {
        this.$message.error("发布失败，请重试！");
      })

    }
  }

}
</script>
<style scoped>
.editor {
  height: 100%;
}

.title {
  margin-top: 10px;
  float: left;
}

.button {
  margin-bottom: 15px;
  margin-top: 7px;
  float: right;
}

</style>
